/*
 * www.acooly.cn Inc.
 * Copyright (c) 2018 All Rights Reserved
 */

/*
 * 修订记录:
 * zhangpu@acooly.cn 2018-01-31 16:37 创建
 */
package com.acooly.module.openapi.client.provider.fudian.notify;


import com.acooly.core.utils.Servlets;
import com.acooly.module.openapi.client.api.notify.NotifyHandlerDispatcher;
import com.acooly.module.openapi.client.provider.fudian.OpenAPIClientFudianProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangpu 2018-01-31 16:37
 */
@Slf4j
@Component("fudianApiServiceClientFilter")
public class FudianApiServiceClientFilter implements Filter {

    private static final int SUCCESS_RESPONSE_CODE = 200;
    private static final String SUCCESS_RESPONSE_BODY = "success";

    @Autowired
    private OpenAPIClientFudianProperties openAPIClientFudianProperties;

    @Resource(name = "fudianNotifyHandlerDispatcher")
    private NotifyHandlerDispatcher notifyHandlerDispatcher;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        try {
            Map<String, Object> received = Servlets.getParametersStartingWith(request, null);
            log.info("Fudian异步通知: {}",received);
            Map<String, String> notifyData = new HashMap<String, String>(received.size());
            for (Map.Entry<String, Object> entry : received.entrySet()) {
                notifyData.put(entry.getKey(), (String) entry.getValue());
            }
            String requestUrl = Servlets.getRequestPath(request);
            notifyHandlerDispatcher.dispatch(requestUrl, notifyData);
            response.setStatus(SUCCESS_RESPONSE_CODE);
            Servlets.writeResponse(response, SUCCESS_RESPONSE_BODY, null);
        } catch (Exception e) {
            Servlets.writeResponse(response, "failure", null);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("Fudian异步通知接受Filter初始化:{}", filterConfig.getFilterName());
    }

    @Override
    public void destroy() {
        log.info("Fudian异步通知接受Filter销毁");
    }

}
